/*
 * @Author: 范非苗
 * @Date: 2025-04-21 16:09:58
 * @LastEditTime: 2025-05-03 09:35:29
 * 气泡框组件
 */

import { useState, useEffect } from 'react'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'

import styles from './Popover.module.less'
function Index({ children, content, width = '60vw' }) {
  const [show, setShow] = useState(false) // 是否展示弹窗
  const [position, setPosition] = useState({ title: { left: 0 }, arrow: { left: 0 } })
  // 气泡弹框
  function onTogglePopover(event) {
    event.stopPropagation()
    setShow(!show)
  }
  useEffect(() => {
    // const systemInfo = Taro.getSystemInfoSync()
    // const { windowWidth } = systemInfo
    const query = Taro.createSelectorQuery().in(this)

    query.select('#title').boundingClientRect()
    query.select('#popover-body').boundingClientRect()
    query.exec((res) => {
      if (res[0] && res[1]) {
        const left = res[0].left
        const popoContentWidth = res[1].width
        const popoContentWidthHalf = popoContentWidth / 2
        // console.log('res1', res[1])
        // console.log('left', left)
        // console.log('popoContentWidthHalf', popoContentWidthHalf)
        setPosition((prevPos) => {
          const l = left >= popoContentWidthHalf ? -popoContentWidthHalf : -left
          return {
            ...prevPos,
            title: {
              left: l
            },
            arrow: {
              left: Math.abs(l)
            }
          }
        })
      }
    })
  }, [show])
  return (
    <View className="ml-1  position-relative font-weight-normal" id="popover">
      <View onClick={(event) => onTogglePopover(event)} id="title">
        {children}
      </View>
      {show && (
        <>
          <View
            className={styles['popover-body']}
            style={{ left: position.title.left, width: width }}
            id="popover-body"
          >
            <View className={styles['popover-arrow']} style={{ left: position.arrow.left }}></View>
            <View className={styles['popover-content']}>{content}</View>
          </View>
        </>
      )}
    </View>
  )
}

export default Index
